<?php
declare(strict_types=1);
namespace Service\ConsumerService\ConsumerUserMapping;
use Service\BaseService;
use Service\UserService\ChannelUserService;
use Service\AppService\SystemCacheConfigService;
use Service\TemplateService\TemplateDeliveryService;
use Service\Code\Normal;
use App\Model\CommodityModel\CommodityChannelBestGoods;
use App\Model\CommodityModel\CommodityOptimizationBbc;
use Service\AppService\IdService;
use Service\CommodityService\GoodsNotifyMessageStorage;
use App\Model\PssModel\Sysconfig;
use Hyperf\Utils\WaitGroup;
use Service\CommodityService\ShopCommodityChange;
use Service\CommodityService\GoodsNotifyType;

/**
 * 自营BBC消费中心
 * @author chenshubo
 */
class ChannelSelfBbcConsumerService extends BaseService
{
    const page_size = 50;
    
    /**
     * 消费者新的全部协程
     * @param string $message_type
     * @param array $body
     */
    public function consumer(string $message_type,array $body = [] )
    {
        $lists = ChannelUserService::instance()->getAllSelfBbcUser();
        if( empty($lists) ) {
            return Normal::returnCode(Normal::SUC,"当前没有渠道需要推送商品信息!");
        }
        
        //推送每个渠道
        $config     = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('channel_task_user_limit');
        $size       = $config['TaskPushChannelUserCount'] ?? self::page_size;
        $size       = (int)$size;
        //获取所有的渠道数据进行分组
        $chunkList  = array_chunk($lists, $size);
        //多渠道同时处理
        $chunkListCount = count($chunkList);
        $wg = new WaitGroup();
        $wg->add($chunkListCount);
        $chunkListSucResult = [];
        $chunkListErrResult = [];
        foreach ($chunkList as $key => $userList) 
        {
            //如果是当前分割的最后的一个用户组，需要追加的云仓商城的特殊用户组处理
            if( $chunkListCount == ($key + 1) ) {
                //此处追加一个商城商品处理
                $shopTemplate = Sysconfig::instance()->getShopTemplate();
                $shopUser = [
                    'id'                    => 0,
                    'bid'                   => 0,
                    'name'                  => '云仓商城',
                    'template'              => $shopTemplate['contents'],
                    'template_price_tpl'    => ''
                ];
                array_push($userList, $shopUser);
            }
            
            co(function () use ($wg,$userList,$message_type,$body,& $chunkListResult,& $chunkListErrResult)
            {
                usleep(10000);
                $result = $this->consumerSingleChannelQueue($message_type,$body,$userList);
                if( $result['code'] == Normal::SUC ) {
                    $chunkListSucResult[] = $result;
                } else {
                    $chunkListErrResult[] = $result;
                }
                $wg->done();
            });
        }
        
        $wg->wait();
        
        if( !empty($chunkListErrResult) ) {
            return Normal::returnCode(Normal::FAIL,"当前渠道商数据消费异常",$chunkListErrResult);
        }
        return Normal::returnCode(Normal::SUC,"消费处理完成");
    }
    
    /**
     * 处理单组用户集群
     * @param string $message_type
     * @param array $body
     * @param array $userList
     */
    public function consumerSingleChannelQueue(string $message_type,array $body = [],array $userList)
    {
        $bids = array_column($userList,'bid');
        if( $message_type == GoodsNotifyType::COMMODITY_ARCHIVE_CHANGE )
        {
            $change_ids = array_unique($body['SkuIDList']);//此处一定要进去去重
            $result = waiter(function() use ($bids,$change_ids,$body)
            {
                return callRpcCommodityServer('getUserSkuIDChange',[
                    'bids'   => $bids,
                    'SkuIDS' => $change_ids,
                ]);
            },-1);
            
            if( $result['code'] != Normal::SUC ) {
                return $result;
            }
            $userBestGoodsList = $result['data'];
            $result_change = $this->channelOptimizationGoodsUpdate($userBestGoodsList,$change_ids);
        }
        else if( $message_type == GoodsNotifyType::SUPPLIER_COMMODITY_CHANGE )
        {
            $change_ids = array_unique($body['SupplierCommodityIDList']);//此处一定要进去去重
            $result = waiter(function() use ($bids,$change_ids,$body)
            {
                return callRpcCommodityServer('getUserSkuIDChange',[
                    'bids'   => $bids,
                    'SupplierSKUIDS' => $change_ids,
                ]);
            },-1);
            if( $result['code'] != Normal::SUC ) {
                return $result;
            }
            $userBestGoodsList = $result['data'];
            $result_change = $this->channelOptimizationGoodsUpdate($userBestGoodsList,$change_ids,false);
        }
        else
        {
            foreach ($userList as $binfo)
            {
                if( $binfo['bid'] == 0 ) {
                    continue;
                }
                GoodsNotifyMessageStorage::instance()->{$message_type}($binfo,$body);
            }
            return Normal::returnCode(Normal::SUC,"处理完成");
        }
        
        if( $result_change['code'] != Normal::SUC )
        {
            return $result_change;
        }
        
        return Normal::returnCode(Normal::SUC,"处理完成");
    }
    
    /**
     * 处理所有增量更新用户
     * @param array $userBestGoodsList
     * @param array $changeGoodsList
     * @param bool $isArchive
     */
    public function channelOptimizationGoodsUpdate( array $userBestGoodsList ,array $change_ids, bool $isArchive = true )
    {
        //获取毛利规则
        $goodsLevelConfig       = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('goods_level');
        //获取默认运费模板
        $defaultTemplateInfo    = TemplateDeliveryService::instance()->getDefaultTemplateInfo();
        
        //多渠道同时处理
        $userBestGoodsListCount = count($userBestGoodsList);
        $userBestGoodsListCo = new \Hyperf\Utils\WaitGroup();
        $userBestGoodsListCo->add($userBestGoodsListCount);
        $resultGoodsChangeCoList = [];
        foreach ($userBestGoodsList as $item)
        {
            co(function () use ($userBestGoodsListCo,$change_ids,$item,$isArchive,& $resultGoodsChangeCoList)
            {
                if( isset($item['code']) && $item['code'] != Normal::SUC ) {
                    $userBestGoodsListCo->done();
                    return;
                }
                
                usleep(2000);
                $binfo          = $item['binfo'];
                $bestGoodsList  = $item['goodsList'];
                if( $isArchive ) {
                    $result_change = $this->bestChangeByAcrchiveGoods($binfo,$change_ids,$bestGoodsList);
                } else {
                    $result_change = $this->bestChangeBySupplierGoods($binfo,$change_ids,$bestGoodsList);
                }
                
                $bid = $binfo['id'];
                if( $result_change['code'] == Normal::SUC ) 
                {
                    if( empty($result_change['data']) ) 
                    {
                        $resultGoodsChangeCoList[$bid]['code']    = 200;
                        $resultGoodsChangeCoList[$bid]['msg']     = '当前未发现满足的数据需要处理';
                        $resultGoodsChangeCoList[$bid]['data']    = [];
                    }
                    else 
                    {
                        $newChangeIds = $result_change['data'];
                        //属于增量更新的用户才进行二次筛选最新满足条件的授权数据,用供应商商品ID
                        //一定要用主档案商品ID来进行比价筛选
                        $resultGoodsChangeCoList[$bid]['code']    = 200;
                        $resultGoodsChangeCoList[$bid]['msg']     = '获取成功';
                        $resultGoodsChangeCoList[$bid]['data']    = [
                            'bid'               => $bid,
                            'IDS'               => $newChangeIds,
                            'bestGoodsList'     => $bestGoodsList,
                            'isArchive'         => true,
                            'binfo'             => $binfo,
                        ];
                    }
                }
                else
                {
                    $resultGoodsChangeCoList[$bid]['code']    = 0;
                    $resultGoodsChangeCoList[$bid]['msg']     = $result_change['msg'];
                    $resultGoodsChangeCoList[$bid]['data']    = [];
                }
                
                $userBestGoodsListCo->done();
            });
        }
        
        $userBestGoodsListCo->wait();
        
        //如果有错误的情况，直接抛出来
        $userChangeList = [];
        foreach ($resultGoodsChangeCoList as $key => $result_item) 
        {
            //错误异常情况
            if( $result_item['code'] != Normal::SUC ) {
                return $result_item;
            }
            
            //未发现可用数据处理
            if( empty($result_item['data']) ) {
                unset($resultGoodsChangeCoList[$key]);
                continue;
            }
            
            //路由用户不参与渠道商品表数据写入
            if( isset($result_item['binfo']['is_router_user']) && $result_item['binfo']['is_router_user'] == 1 ) 
            {
                unset($resultGoodsChangeCoList[$key]);
                continue;
            }
            
            array_push($userChangeList,$result_item['data']);
        }
        if( empty($userChangeList) ) {
            return Normal::returnCode(Normal::SUC,"当前没有数据需要处理");
        }
        
        return $this->channelGoodsChangeNotify($userChangeList,$goodsLevelConfig,$defaultTemplateInfo);
    }

    
    
    /**
     * 获取最新授权数据并且写入待推送渠道商品池
     * @param array $userChangeList
     * @param array $goodsLevelConfig
     * @param array $defaultTemplateInfo
     * @return mixed
     */
    public function channelGoodsChangeNotify(array $userChangeList, array $goodsLevelConfig ,array $defaultTemplateInfo)
    {
        //组装变化数据清单
        $userChangeListMap = array_column($userChangeList,null,'bid');
        
        //得到最新授权数据
        $result = callRpcCommodityServer('getCopAuthGoodsList',$userChangeList);
        if( $result['code'] != Normal::SUC ) {
            return $result;
        }
        
        $ChannelBestGoodsList = $result['data'];
        //多渠道同时处理
        $chanelUserCount = count($ChannelBestGoodsList);
        $channelUserCo = new \Hyperf\Utils\WaitGroup();
        $channelUserCo->add($chanelUserCount);
        
        $multiUserConsumerError = [];
        //判断当前渠道商户数据是否发生变化
        foreach ($ChannelBestGoodsList as $bid => $userGoodsList )
        {
            co(function () use ($channelUserCo,$userGoodsList,$bid,$userChangeListMap,$goodsLevelConfig,$defaultTemplateInfo,& $multiUserConsumerError)
            {
                usleep(2000);
                $userChangeList = $userChangeListMap[$bid];
                //是否主档案
                $isArchive  = $userChangeList['isArchive'];
                $change_ids = $userChangeList['IDS'];
                $binfo      = $userChangeList['binfo'];
                $source     = $isArchive ? 1 : 2 ;
                
                if( empty($userGoodsList) )
                {
                    CommodityChannelBestGoods::instance()->getTableByBuID($bid)->where('BuID',$bid)->whereIn('SkuID',$change_ids)->update([
                        'CommodityStatus'   => 0,
                        'UpdateTime'        => date("Y-m-d H:i:s")
                    ]);
                    $channelUserCo->done();
                    return;
                }
                
                $userGoodsListMap = array_column($userGoodsList,null,'SkuID');
                $hasChangeIds = array_keys($userGoodsListMap);
                $diff_change_ids = array_diff($change_ids,$hasChangeIds);
                if( !empty($diff_change_ids) ) {
                    CommodityChannelBestGoods::instance()->getTableByBuID($bid)->where('BuID',$bid)->whereIn('SkuID',$diff_change_ids)->update([
                        'CommodityStatus'   => 0,
                        'UpdateTime'        => date("Y-m-d H:i:s")
                    ]);
                }
                
                //同一渠道多商品同时处理
                $userGoodsCount = count($userGoodsListMap);
                $userGoodsCo = new \Hyperf\Utils\WaitGroup();
                $userGoodsCo->add($userGoodsCount);
                $hasError = [];
                foreach ($userGoodsListMap as $goods )
                {
                    co(function () use ($userGoodsCo,$binfo,$goods,$source,$goodsLevelConfig,$defaultTemplateInfo,& $hasError)
                    {
                        usleep(2000);
                        $bid = $binfo['id'];
                        
                        //查询是否写入了数据
                        $SkuID = $goods['SkuID'];
                        $row = CommodityChannelBestGoods::instance()->getTableByBuID($bid)->where('BuID',$bid)->where('SkuID',$SkuID)->first();
                        $time = date("Y-m-d H:i:s");
                        $base_data = [
                            'BuID'                      => $bid,
                            'SkuID'                     => $SkuID,
                            'SupplierSKUID'             => $goods['SupplierCommodityID'],
                            'StockInfoID'               => $goods['StockInfoID'],
                            'SpecList'                  => $goods['SpecList'],
                            'CommodityStatus'           => 1,
                            'CommodityOptimizationID'   => $goods['CopID'],
                            'CreateTime'                => $time
                        ];
                        if( empty($row) ) {
                            $base_data['ID']            = IdService::instance()->getOtherID();
                            $base_data['CreateTime']    = $time;
                            CommodityChannelBestGoods::instance()->getTableByBuID($bid)->insert($base_data);
                        } else {
                            $base_data['UpdateTime'] = $time;
                            CommodityChannelBestGoods::instance()->getTableByBuID($bid)->where('ID',$row['ID'])->update($base_data);
                        }
                        
                        //组装推送报文渠道商品报文
                        if( $bid > 0 )
                        {
                            $args = [
                                'bid'   => $bid,
                                'skuids' => [(string)$SkuID],
                                'query_type' => 1,
                                'pageLastID' => ''
                            ];
                            $result = callRpcCommodityServer('getUserPushGoodsList',$args);
                            if( $result['code'] == Normal::SUC ) {
                                //写入增量变化的商品数据
                                GoodsNotifyMessageStorage::instance()->goodsChange($binfo,$result['data'],$source);
                            } else {
                                $hasError[$SkuID] = $result;
                            }
                        } else {
                            //推送到商城队列
                            $searchGoodsList = ShopCommodityChange::instance()->getSearchGoodsListByColumns([$goods]);
                            ShopCommodityChange::instance()->recoverShopActivityGoodsUpBySkuIDS([(string)$goods['SkuID']]);
                            ShopCommodityChange::instance()->goodsChange($searchGoodsList);
                        }
                        
                        $userGoodsCo->done();
                    });
                }
                
                //结束当前协程
                $userGoodsCo->wait();
                $channelUserCo->done();
                
                if( !empty($hasError) ) {
                    $multiUserConsumerError[$bid] = $hasError;
                }
            });
        }
        
        $channelUserCo->wait();
        
        //判断是否某个用户出现消费商品异常消息
        if( !empty($multiUserConsumerError) ) {
            $errorMsg = json_encode($multiUserConsumerError,JSON_UNESCAPED_UNICODE);
            return Normal::returnCode(Normal::FAIL,"云仓增量更新消费商品消息出现异常【{$errorMsg}】");
        }
        
        return Normal::returnCode(Normal::SUC,"处理完成");
    }


     /**
     * 处理增量更新逻辑根据主供应商商品ID
     * @param array $binfo
     * @param array $changeSkuIds
     * @param array $BestGoodsList
     */
    public function bestChangeBySupplierGoods(array $binfo,array $changeIds,array $bestGoodsList)
    {
        $bid                = $binfo['id'];
        $bestGoodsListMap   = array_column($bestGoodsList,null,'SupplierSKUID');
        $updateTime         = date("Y-m-d H:i:s");
        
        //拿出不在优选池里面的数据
        $changeGoodsSupplierSkuIds = array_keys($bestGoodsListMap);
        $diffGoodsDownSupplierSkuIds = array_diff($changeIds,$changeGoodsSupplierSkuIds);

        //如果变化的供应商商品资料为空，需要处理已存在优选池的数据（主档案是推送变更还是下架）
        $change_sku_ids = [];
        if( !empty($diffGoodsDownSupplierSkuIds) ) 
        {
            
            $copList        = CommodityOptimizationBbc::instance()->getCopListBySupplierSkuIdAndSkuIds($bid,$diffGoodsDownSupplierSkuIds);
            $copListMap     = array_column($copList,null,'SupplierSKUID');
            
            $skuGroup       = [];
            $skuCodeMap     = array_column($copList,'SkuID','SKUCode');
            $skuCodeList    = array_keys($skuGroup);
            
            //查询当前sku下其它供应商商品集合
            $copSkuList = CommodityOptimizationBbc::instance()
            ->getTableByBuID($bid)
            ->where('BuID',$bid)
            ->whereIn('SkuID',$skuCodeMap)
            ->where('CommodityStatus',1)
            ->get()
            ->toArray();
            
            $copSkuListMap = [];
            foreach ($copSkuList as $item)
            {
                $copSkuListMap[$item['SKUCode']][$item['SupplierSKUID']] = $item;
            }
            
            //查询是否需要下架的主档案
            $down_sku_list      = [];
            $down_sku_ids       = [];
            $down_cop_ids       = [];
            foreach ($copSkuListMap as $skucode => $copInfoList)
            {
                foreach ($copInfoList as $supplier_sku_id => $copInfo)
                {
                    //需要下架供应商商品
                    if( in_array($supplier_sku_id, $changeIds) )
                    {
                        $down_cop_ids[] = $copInfo['ID'];
                        unset($copInfoList[$supplier_sku_id]);
                    }
                }
                
                if( empty($copInfoList) ) {
                    $down_sku_list[] = $skucode;
                    $down_sku_ids[] = $skuCodeMap[$skucode];
                } else {
                    $change_sku_ids[] = $skuCodeMap[$skucode];
                }
            }
            
            //存在需要下架优选池的数据ID
            if( !empty($down_cop_ids) ) {
                CommodityOptimizationBbc::instance()
                ->getTableByBuID($bid)
                ->whereIn('ID',$down_cop_ids)
                ->update([
                    'CommodityStatus'   => 0,
                    'UpdateTime'        => $updateTime,
                ]);
            }
            
            //存在需要下架的主档案
            if( !empty($down_sku_list) ) {
                
                if( $bid > 0 ) {
                    if( $binfo['is_router_user'] != 1 ) {
                        //推送三方渠道
                        $result  = GoodsNotifyMessageStorage::instance()->goodsSkuChange($binfo,$down_sku_list,2);
                        if( $result['code'] != Normal::SUC ) {
                            return $result;
                        }
                    }
                } else {
                    //推送到商城队列
                    ShopCommodityChange::instance()->removeShopActivityGoodsDownBySkuIDS($down_sku_ids);
                    $result = ShopCommodityChange::instance()->goodsDel($down_sku_ids);
                    if( $result['code'] != Normal::SUC ) {
                        return $result;
                    }
                }
            }
            
            //需要下架渠道商品表数据
            if( !empty($down_sku_ids) ) {
                
                //查询数据
                $hasChannelData = CommodityChannelBestGoods::instance()
                ->getTableByBuID($bid)->where('BuID',$bid)
                ->whereIn('SkuID',$down_sku_ids)
                ->get()->toArray();
                
                if( !empty($hasChannelData) ) {
                    $hasRowsIds = array_column($hasChannelData,'ID');
                    $update_status_data = [
                        'CommodityStatus'   => 0,
                        'UpdateTime'        => $updateTime,
                    ];
                    CommodityChannelBestGoods::instance()->getTableByBuID($bid)->whereIn('ID',$hasRowsIds)->update($update_status_data);
                }
            }
        }
        
        //供应商商品变化最新数据
        if( empty($bestGoodsList) ) {
            if( !empty($change_sku_ids) ) {
                return Normal::returnCode(Normal::SUC,"获取成功",$change_sku_ids);
            }
            return Normal::returnCode(Normal::SUC,"当前供应商档案变更无须数据处理");
        }
        
        
        //查询满足商品优选池的数据
        $count = count($bestGoodsList);
        $wg = new WaitGroup();
        $wg->add($count);
        foreach ($bestGoodsList as $bestGoods)
        {
            co(function () use ($wg,$bestGoods,$bid,$binfo,$updateTime)
            {
                $copInfo = CommodityOptimizationBbc::instance()
                ->getTableByBuID($bid)
                ->where('BuID',$bid)
                ->where('SkuID',$bestGoods['SkuID'])
                ->where('SupplierSKUID',$bestGoods['SupplierSKUID'])
                ->first();
                
                //如果存在变化的数据
                if( !empty($copInfo) )
                {
                    $copInfo = $copInfo->toArray();
                    //如果存在历史数据，则更新
                    $this->commodityCopUpdate($bestGoods, $updateTime, $bid,$copInfo);
                } else {
                    //如果当前渠道,共享库存不足的情况下并且有锁库的情况，需要给下游推送变更或者下架,剔除
                    $this->commodityCopInsert($bestGoods, $updateTime, $bid,$binfo);
                }
                $wg->done();
            });
        }
        $wg->wait();
        $bestGoodsSkuIds   = array_column($bestGoodsList,'SkuID');
        $change_sku_ids    = array_merge($change_sku_ids,$bestGoodsSkuIds);
        $change_sku_ids    = array_unique($change_sku_ids);
        return Normal::returnCode(Normal::SUC,"获取成功",$change_sku_ids);
    }
    /**
     * 处理增量更新逻辑根据主资料ID
     * @param array $binfo
     * @param array $changeSkuIds
     * @param array $bestGoodsList
     */

     public function bestChangeByAcrchiveGoods(array $binfo, array $changeSkuIds, array $bestGoodsList)
    {
        $bid                = $binfo['id'];
        $bestGoodsListMap   = array_column($bestGoodsList,null,'SupplierSKUID');
        $updateTime         = date("Y-m-d H:i:s");
        
        //拿出不在优选池里面的数据
        $bestGoodsListMap   = array_column($bestGoodsList,null,'SkuID');
        $bestGoodsSkuIds    = array_keys($bestGoodsListMap);
        $diffSkuIds         = array_diff($changeSkuIds,$bestGoodsSkuIds);
        
        //如果变动的数据里面，没有发现商品最新优选数据走下面逻辑
        if( !empty($diffSkuIds) )
        {
            //查询商品池是否存在已上架的数据
            $hasUp = CommodityOptimizationBbc::instance()
            ->getTableByBuID($bid)
            ->where('BuID',$bid)
            ->whereIn('SkuID',$diffSkuIds)
            ->where('CommodityStatus',1)
            ->get()
            ->toArray();
            
            $hasUpSkuMap = array_column($hasUp,'SKUCode','SkuID');
            $update_skuids = array_keys($hasUpSkuMap);
            
            //更新商品优选池全部下架
            if( $update_skuids )//换成主键ID更新
            {
                $hasRowsIds = array_column($hasUp,'ID');
                
                //更新商品优选池下架
                $update_status_data = [
                    'CommodityStatus'   =>  0,
                    'UpdateTime'        => $updateTime,
                ];
                CommodityOptimizationBbc::instance()->getTableByBuID($bid)->whereIn('ID',$hasRowsIds)->update($update_status_data);
                
                //查询数据
                $hasChannelData = CommodityChannelBestGoods::instance()
                ->getTableByBuID($bid)->where('BuID',$bid)
                ->whereIn('SkuID',$update_skuids)
                ->get()->toArray();
                
                if( !empty($hasChannelData) ) {
                    $hasRowsIds = array_column($hasChannelData,'ID');
                    CommodityChannelBestGoods::instance()->getTableByBuID($bid)->whereIn('ID',$hasRowsIds)->update($update_status_data);
                }
                
                if( $bid > 0 ) {
                    if( $binfo['is_router_user'] != 1 ) {
                        //推送三方渠道
                        $sku_codes = array_values($hasUpSkuMap);
                        return GoodsNotifyMessageStorage::instance()->goodsSkuChange($binfo,$sku_codes,1);
                    }
                } else {
                    //推送到商城队列
                    ShopCommodityChange::instance()->removeShopActivityGoodsDownBySkuIDS($update_skuids);
                    return ShopCommodityChange::instance()->goodsDel($update_skuids);
                }
            }
        }
        
        //查询满足商品优选池的数据
        $count = count($bestGoodsList);
        $wg = new WaitGroup();
        $wg->add($count);
        foreach ($bestGoodsList as $goods)
        {
            co(function () use ($wg,$goods,$bid,$updateTime,$binfo)
            {
                usleep(2000);
                $SkuID          = $goods['SkuID'];
                $SupplierSKUID  = $goods['SupplierSKUID'];
                $copInfo        = CommodityOptimizationBbc::instance()
                ->getTableByBuID($bid)
                ->where('BuID',$bid)
                ->where('SkuID',$SkuID)
                ->where('SupplierSKUID',$SupplierSKUID)
                ->first();
                
                //如果存在历史数据，则更新
                if( ! empty($copInfo) ) {
                    $copInfo = $copInfo->toArray();
                    $this->commodityCopUpdate($goods, $updateTime,$bid,$copInfo);
                } else {
                    $this->commodityCopInsert($goods, $updateTime,$bid,$binfo);
                }
                $wg->done();
            });
        }
        $wg->wait();
        if( !empty($bestGoodsSkuIds) ) {
            return Normal::returnCode(Normal::SUC,"获取成功",$bestGoodsSkuIds);
        }
        return Normal::returnCode(Normal::SUC,"当前主档案变更无须数据处理");
    }

     /**
     * 优选商品池写入
     * @param array $goods
     * @param string $UpdateTime
     * @param $bid
     * @param array $binfo
     */
    public function commodityCopInsert( array $goods,string $updateTime,$bid,$binfo)
    {
        if( !($goods['StockRemainNumber'] <= 0 && $goods['Number'] <= 0 && $goods['NumberLock'] > 0) ) {
            $insert = [
                'ID'                        => IdService::instance()->getOtherID(),
                'BuID'                      => $bid,
                'SkuID'                     => $goods['SkuID'],
                'SKUCode'                   => $goods['SKUCode'],
                'SupplierSKUID'             => $goods['SupplierSKUID'],
                'SupplierSKUCode'           => $goods['SupplierSKUCode'],
                'StockInfoID'               => $goods['StockInfoID'],
                'BatchNo'                   => $goods['BatchNo'],
                'SpecList'                  => $goods['SpecList'],
                'BatchSpecMinSinglePrice'   => $goods['BatchSpecMinSinglePrice'],
                'IsInit'                    => 1,
                'PriceScaleRule'            => $binfo['template_price_tpl'],
                'CreateTime'                => $updateTime,
            ];
            CommodityOptimizationBbc::instance()->getTableByBuID($bid)->add($insert);
        }
    }

     /**
     * 优选商品池更新
     * @param array $goods
     * @param string $UpdateTime
     * @param int $bid
     * @param array $copInfo
     */
    public function commodityCopUpdate( array $goods,string $updateTime,$bid,array $copInfo)
    {
        $_cop_id = $copInfo['ID'];
        //如果当前渠道,共享库存不足的情况下并且有锁库的情况，需要给下游推送变更或者下架,并且删除已进入优选池的数据
        if( $goods['StockRemainNumber'] <= 0 && $goods['Number'] <= 0 && $goods['NumberLock'] > 0 )
        {
            CommodityOptimizationBbc::instance()
            ->getTableByBuID($bid)
            ->where('ID',$_cop_id)
            ->update([
                'CommodityStatus'   => 0,
                'UpdateTime'        => $updateTime,
            ]);
            return;
        }
        
        //如果是固定价格
        if( $copInfo['PriceRuleType'] == 2 )
        {
            //获取最新原始成本价
            $newGoodsSpecList       = @json_decode($goods['SpecList'],true);
            $newGoodsSpecListMap    = array_column($newGoodsSpecList,null,'SpecificationNum');
        
            //已存在的规格价格
            $oldSpecList = @json_decode($copInfo['SpecList'],true);
            foreach ($oldSpecList as $key => & $spec )
            {
                $SpecificationNum = $spec['SpecificationNum'];
                if( isset($newGoodsSpecListMap[$SpecificationNum])) {
                    //只更新先有的供货价格
                    $spec['SpecificationPrice'] = $newGoodsSpecListMap[$SpecificationNum]['SpecificationPrice'];
                    //更新包邮1供货价
                    if (!empty($newGoodsSpecListMap[$SpecificationNum]['SpecificationFreightPrice'])){
                        $spec['SpecificationFreightPrice'] = $newGoodsSpecListMap[$SpecificationNum]['SpecificationFreightPrice'];
                    }
                }
            }
        
            $goodsSpecList = json_encode($oldSpecList,JSON_UNESCAPED_UNICODE);
        } else {
            //非固定价格，直接更新
            $goodsSpecList = $goods['SpecList'];
        }
        $updateArr = [
            'SkuID'                     => $goods['SkuID'],
            'SKUCode'                   => $goods['SKUCode'],
            'SupplierSKUID'             => $goods['SupplierSKUID'],
            'BatchNo'                   => $goods['BatchNo'],
            'StockInfoID'               => $goods['StockInfoID'],
            'BatchSpecMinSinglePrice'   => $goods['BatchSpecMinSinglePrice'],
            'SpecList'                  => $goodsSpecList,
            'IsInit'                    => 1,
            'CommodityStatus'           => 1,
            'UpdateTime'                => $updateTime,
        ];
        CommodityOptimizationBbc::instance()
        ->getTableByBuID($bid)
        ->where('ID',$_cop_id)
        ->update($updateArr);
        return;
    }
    
}